package com.java1412.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Map;

/**
 * @author java1412
 * @since 2023-08-08 09:58:05
 */
public class JWTUtil {
    // 定义密钥
    private static final String TOKEN = "token!Q@W3e4r";

    /**
     * 生成token
     *
     * @param map
     * @return
     */
    public static String getToken(Map<String, String> map) {
        // 创建builder对象
        JWTCreator.Builder builder = JWT.create();
        // 对map进行遍历
        map.forEach((k, v) -> {
            builder.withClaim(k, v);
        });
        // 创建日历对象
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.SECOND, 1800); // 过期时间是30分钟
        // 设置过期时间
        builder.withExpiresAt(instance.getTime());
        return builder.sign(Algorithm.HMAC256(TOKEN)).toString();
    }

    /**
     * 验证token
     *
     * @param token
     * @return
     */
    public static DecodedJWT verify(String token) {
        return JWT.require(Algorithm.HMAC256(TOKEN)).build().verify(token);
    }

    /**
     * 获取token中payload
     *
     * @param token
     * @return
     */
    public static DecodedJWT getToken(String token) {
        return JWT.require(Algorithm.HMAC256(TOKEN)).build().verify(token);
    }
}
